"use strict";
const Result = require("../basics/result");
const AlarmModel = require("../model/app_alarm");
/**
 * 主方法执行
 */
exports.execute = async (ctl, mothed, context) => {
  let message = { code: 0, context: null };
  try {
    console.log(ctl.name + "---" + mothed + "---执行:");
    const data = await new ctl(context)[mothed]();
    return Result.success(data);
  } catch (error) {
    if (error.code) {
      message.code = error.code;
    } else {
      message.code = Result.constant.otherfail;
    }
    message.context = error;
  }
  if (message.code == Result.constant.otherfail || message.code == Result.constant.dbfail || message.code == Result.constant.taobaofail) {
    await AlarmModel.getInstant(context.cloud).addOne("mothed:" + mothed + ",openId:" + context.openId + ",error:" + JSON.stringify(message));
  }
  return Result.error(message.code, message.context);
};

/**
 * 淘宝方法执行
 */
exports.taobao = async (cloud, api, data = {}) => {
  try {
    const result = await cloud.topApi.invoke({
      api: api,
      autoSession: true,
      data: data
    });
    return result;
  } catch (error) {
    console.log(api + "错误:", error);
    let res = Result.error(Result.constant.taobaofail, error.sub_msg);
    res.data = error;
    throw res;
  }
};

/**
 * 淘宝方法执行
 */
exports.taobaoInvoke = async (cloud, api, data = {}) => {
  try {
    const result = await cloud.topApi.invoke({
      api: api,
      data: data
    });
    console.log("result", result);
    return result;
  } catch (error) {
    console.log(api + "错误:", error);
    let res = Result.error(Result.constant.taobaofail, error.sub_msg);
    res.data = error;
    throw res;
  }
};